package com.hyf.rabbitmq.topic;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ReceivedLogsTopic1 {

    private static final String EXCHANGES_NAME="topic_logs";

    public static void main(String[] args){
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("12345");

        Connection connection =null;
        Channel channel=null;
        try {
            connection=connectionFactory.newConnection();
            channel = connection.createChannel();

            channel.exchangeDeclare(EXCHANGES_NAME, BuiltinExchangeType.TOPIC);
            String queueName = channel.queueDeclare().getQueue();
            String[] routingKes=new String[]{"*.orange.*"};
            for(String routingKey:routingKes){
                channel.queueBind(queueName,EXCHANGES_NAME,routingKey);
                System.out.println(String.format("ReceiveLogsTopic1 exchange:%s,queueName:%s,severity:%s",EXCHANGES_NAME,queueName,routingKey));
            }

            System.out.println(" ReceiveLogsTopic1 wait.....");

            Consumer consumer=new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message=new String(body,"utf-8");
                    System.out.println(String.format("ReceivedLogsTopic1 [x1] routingKey:%s message:%s",envelope.getRoutingKey(),message));
                }
            };

            channel.basicConsume(queueName,true,consumer);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally{
            /*if(channel!=null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/

        }

    }
}

